import { getUserInfo, login } from '@/api/user'
import { constantRoutes } from '@/router'
import { getToken, removeToken, setToken } from '@/utils/auth'

const state = {
  token: getToken(),
  userInfo: {},
  routers: constantRoutes,
  addPoints: []
}
const mutations = {
  // 设置token,将获取倒的新token值保存到vuex和本地存储中
  setToken(state, newtoken) {
    state.token = newtoken
    setToken(newtoken)
  },
  // 移除token,将token从vuex和本地存储中移除
  removeTokenFn(state) {
    state.token = null
    removeToken()
  },
  getUserInfo(state, data) {
    state.userInfo = data
  },
  // 设置路由
  setRouters(state, newRouters) {
    state.routers = [...constantRoutes, ...newRouters]
    console.log('user中的路由', state.routers)
  }
}
const actions = {
  async loginFn(context, data) {
    // 发送异步请求，获取token
    // console.log(data)
    const res = await login(data)
    // console.log(res)
    context.commit('setToken', res)
  },
  async setUserInfo(context) {
    const res = await getUserInfo()
    context.commit('getUserInfo', res)
    return res
  },
  async logout(context) {
    await context.commit('removeTokenFn')// 移除token
    context.commit('getUserInfo', {})// 移除用户信息
  }
}
const getters = {}
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
